<template>
  <!-- 弹窗组件，点击遮罩层触发 maskClick 事件，居中显示，圆角顶部 -->
    <!-- 商品属性弹窗内容区域 -->
    <view v-if="cartAttr" class="product-window"
      :class="(cartAttr ? 'on' : '') + ' ' + (iSbnt?'join':'') + ' ' + (iScart?'joinCart':'')">
      <!-- 商品图片与信息 -->
      <view class="textpic acea-row row-between-wrapper">
        <!-- 商品图片，点击触发 showImg 事件 -->
        <view class="pictrue" @click="$emit('showImg')">
          <image :src="productSelect.image"></image>
        </view>
        <view class="text">
          <view class="line1">
            {{ productSelect.name }} <!-- 商品名称 -->
          </view>
          <view class="money">
            <view class="mt-12">
              <text class="stock">
                <!-- 库存显示，拼团时显示 groupStock，否则显示普通库存 -->
                库存:{{productSelect.stock || productSelect.transferOutStoreThenStock}}
              </text>
            </view>
          </view>
        </view>
        <!-- 关闭按钮，点击触发 closeAttr 事件 -->
        <view class="iconfont icon-guanbi" @click="$emit('closeAttr')"></view>
      </view>
      <view class="rollTop">
        <!-- 商品属性选择列表 -->
        <view class="productWinList">
          <view class="item" v-for="(item, indexw) in productAttr" :key="indexw">
            <view class="title">{{ item.attrName }}</view> <!-- 属性名，如颜色、尺码等 -->
            <view class="listn acea-row row-middle">
              <!-- 属性选项列表 -->
              <view class="itemn flex"
                :class="[
                  item.index === itemn.optionName ? 'on' : '',
                  isOptionDisabled(item, itemn.optionName, indexw) ? 'disabled' : ''
                ]"
                v-for="(itemn, indexn) in item.optionList"
                @click="!isOptionDisabled(item, itemn.optionName, indexw) && tapAttr(indexw, indexn, item)"
                :key="indexn"
                :style="onlyReduceOnSizeChange && sizeChangeIndex !== '' && productSelect.max_num !== undefined ? 'pointer-events: none; opacity: 0.5;' : ''">
                <!-- 属性图片（如有） -->
                <!-- <image v-if="itemn.image" class="attr-img" :src="itemn.image" alt="" srcset="" /> -->
                <text class="option-name">{{ itemn.optionName }}</text>
              </view>
            </view>
          </view>
        </view>
        <!-- 数量选择区域 -->
        <view class="cart acea-row">
          <view class="title">数量</view>
          <view class="carnum acea-row row-left">
            <!-- 减号按钮，最小为1 -->
            <view v-if="!isProductType" class="item reduce"
              :class="productSelect.cart_num <= 1 ? 'on' : ''"
              @click="changeCartNum(-1)">
              -
            </view>
            <!-- 数量输入框 -->
            <view class='item num'>
              <input type="number" :always-embed="true" :adjust-position="true" cursor-spacing="50"
                :disabled="isProductType"
                v-model.number="productSelect.cart_num"
                :data-name="'productSelect.cart_num'"
                :min="1"
                :max="productSelect.stock"
                @input="onInputCartNum"
                maxlength="3">
            </view>
            <!-- 加号按钮，最大为库存或 max_num -->
            <view class="item plus"
              :class="productSelect.cart_num >= productSelect.stock ? 'on': ''"
              @click="changeCartNum(1)">
              +
            </view>
          </view>
        </view>
        <view class="btn-confirm-wrapper">
          <view class="btn-cancel" @click="$emit('closeAttr')">取消</view>
          <view class="btn-confirm" @click="confirmShipment">确认添加</view>
        </view>
      </view>
    </view>
</template>

<script>
export default {
  name: 'ProductCttr', // 组件名称
  props: {
    cartAttr: Boolean, // 控制弹窗显示
    iSbnt: Boolean, // 是否加入按钮样式
    iScart: Boolean, // 是否加入购物车样式
    productSelect: {
      type: Object,
      required: true // 当前选中的商品信息
    },
    productAttr: {
      type: Array,
      required: true // 商品属性列表
    },
    marketingType: {
      type: Number,
      default: 0 // 营销类型，0为普通
    },
    productType: {
      type: Number,
      default: 0 // 商品类型
    },
    onlyReduceOnSizeChange: {
      type: Boolean,
      default: false // 是否只允许减少数量（如尺码变更时）
    },
    sizeChangeIndex: {
      type: [String, Number],
      default: '' // 尺码变更索引
    },
    isProductType: {
      type: Boolean,
      default: false // 是否为特殊商品类型，影响数量输入
    },
    skuList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    cartAttr :{
      handler(newVal) {
        console.log(newVal)
      if (newVal && this.productSelect && this.productSelect.sku && this.skuList && this.skuList.length) {
        // 找到当前sku对应的attrValue
        const sku = this.skuList.find(s => s.sku === this.productSelect.sku);
        if (sku) {
          const attrValue = typeof sku.attrValue === 'string' ? JSON.parse(sku.attrValue) : sku.attrValue;
          this.productAttr.forEach(attr => {
            if (attrValue[attr.attrName]) {
              this.$set(attr, 'index', attrValue[attr.attrName]);
            }
          });
        }
      }
      },
      immediate: true
    }
  },
  methods: {
    confirmShipment() {
      this.$emit('confirmShipment');
    },
    // 属性选项点击事件，向父组件传递选中的属性
    tapAttr(indexw, indexn, item) {
      // 设置当前属性的 index 为选中的 optionName
      this.$set(this.productAttr[indexw], 'index', item.optionList[indexn].optionName);
      // 查找当前选中组合的 sku
      const selected = this.productAttr.map(attr => attr.index).join(',');
      // 假设所有 sku 信息在 productValue 中（如无则需传递 skuList）
      if (this.skuList) {
        const sku = this.skuList.find(sku => {
          const attrValue = JSON.parse(sku.attrValue);
          return this.productAttr.every(attr => attr.index && attrValue[attr.attrName] === attr.index);
        });
                console.log('sku', sku);

        if (sku && sku.sku) {
          this.productSelect.stock = sku.transferOutStoreThenStock;
          this.productSelect.max_num = sku.transferOutStoreThenStock;
          this.productSelect.price = sku.price;
          this.productSelect.image = sku.image;
          this.productSelect.sku = sku.sku;
          this.productSelect.id = sku.id;
            // 数量不能超过新规格的库存
        if (this.productSelect.cart_num > sku.transferOutStoreThenStock) {
            this.productSelect.cart_num = sku.transferOutStoreThenStock;
          }
        }
      }
      this.$emit('tapAttr', indexw, indexn, item);
    },
    changeCartNum(delta) {
      let num = this.productSelect.cart_num + delta;
      if (num < 1) num = 1;
      if (num > this.productSelect.stock) num = this.productSelect.stock;
      this.productSelect.cart_num = num;
    },
    onInputCartNum(e) {
      let val = Number(e.detail.value);
      if (!val || val < 1) val = 1;
      if (val > this.productSelect.stock) val = this.productSelect.stock;
      this.productSelect.cart_num = val;
    },
    isOptionDisabled(attrItem, optionName, attrIndex) {
      // 1. 复制当前所有已选
      const selected = this.productAttr.map(a => a.index);
      // 2. 替换当前属性为待判断的 optionName
      selected[attrIndex] = optionName;
      // 3. 检查 skuList 是否有该组合
      return !this.skuList.some(sku => {
        const attrValue = JSON.parse(sku.attrValue);
        return this.productAttr.every((attr, idx) => {
          // idx === attrIndex 用 optionName，否则用已选
          const val = idx === attrIndex ? optionName : attr.index;
          // 未选的属性不参与判断
          if (!val) return true;
          return attrValue[attr.attrName] === val;
        });
      });
    }
  }
};
</script>

<style scoped>
/* 商品属性弹窗样式 */
.product-window {
  position: fixed;
  bottom: 0;
  width: 100%;
  left: 0;
  background-color: #fff;
  z-index: 77;
  border-radius: 16rpx 16rpx 0 0;
  padding-bottom: 100rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
  transform: translate3d(0, 100%, 0);
  transition: all .2s cubic-bezier(0, 0, .25, 1);
}
.product-window.on {
  transform: translate3d(0, 0, 0);
}
.product-window.join {
  padding-bottom: 30rpx;
}
.product-window.joinCart {
  padding-bottom: 30rpx;
  z-index: 999;
}
.product-window .textpic {
  padding: 0 130rpx 0 24rpx;
  margin-top: 29rpx;
  position: relative;
}
.product-window .textpic .pictrue {
  width: 150rpx;
  height: 150rpx;
}
.product-window .textpic .pictrue image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}
.product-window .textpic .text {
  width: 424rpx;
  font-size: 28rpx;
  color: #333333;
}
.product-window .textpic .text .money {
  font-size: 28rpx;
  margin-top: 12rpx;
}
.product-window .textpic .text .money .num {
  font-family: PingFang SC;
  font-size: 36rpx;
  font-weight: 600;
}
.product-window .textpic .text .money .stock {
  color: #999;
}
.product-window .textpic .iconfont {
  position: absolute;
  right: 30rpx;
  top: -5rpx;
  font-size: 35rpx;
  color: #8a8a8a;
}
.product-window .rollTop {
  max-height: 760rpx;
  overflow: auto;
  margin-top: 36rpx;
}
.product-window .productWinList .item~.item {
  margin-top: 36rpx;
}
.product-window .productWinList .item .title {
  font-size: 28rpx;
  color: #999;
  padding: 0 30rpx;
}
.product-window .productWinList .item .listn {
  padding: 0 30rpx 0 16rpx;
}
.product-window .productWinList .item .listn .itemn {
  border: 1px solid #F2F2F2;
  font-size: 26rpx;
  color: #282828;
  padding: 4rpx 0;
  border-radius: 8rpx;
  margin: 20rpx 0 0 14rpx;
  background-color: #F2F2F2;
}
.product-window .productWinList .item .listn .itemn .attr-img {
  width: 37rpx;
  height: 37rpx;
  margin-right: 12rpx;
  border-radius: 8rpx;
  margin: 0 -8rpx 0 4rpx;
}
.product-window .productWinList .item .listn .itemn .option-name {
  margin: 0 20rpx 0;
}
.product-window .productWinList .item .listn .itemn.on {
  border: 1px solid #1DB0FC;
  background: #EAF7FF;
  color: #1DB0FC;
}
.product-window .productWinList .item .listn .itemn.limit {
  color: #999;
  text-decoration: line-through;
}
.product-window .cart {
  margin-top: 50rpx;
  margin-bottom: 30rpx;
  padding: 0 24rpx;
}
.product-window .cart .title {
  font-size: 30rpx;
  color: #999;
}
.product-window .cart .carnum {
  height: 54rpx;
}
.product-window .cart .carnum view {
  width: 84rpx;
  text-align: center;
  height: 100%;
  line-height: 54rpx;
  color: #282828;
  font-size: 45rpx;
}
.product-window .cart .carnum .reduce {
  border-right: 0;
  border-radius: 6rpx 0 0 6rpx;
  line-height: 48rpx;
}
.product-window .cart .carnum .reduce.on {
  color: #DEDEDE;
  font-size: 44rpx;
}
.product-window .cart .carnum .plus {
  border-left: 0;
  border-radius: 0 6rpx 6rpx 0;
  line-height: 46rpx;
}
.product-window .cart .carnum .plus.on {
  border-color: #e3e3e3;
  color: #dedede;
}
.product-window .cart .carnum .num {
  background: rgba(242, 242, 242, 1);
  color: #282828;
  font-size: 28rpx;
  border-radius: 12rpx;
  line-height: 54rpx;
  height: 54rpx;
}
.product-window .cart .carnum .num input {
  display: -webkit-inline-box;
  line-height: 54rpx;
  height: 54rpx;
}
.groupOn {
  background: #EAF7FF !important;
  border: 1px solid #1DB0FC !important;
  color: #1DB0FC !important;
}
.btn-confirm-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 24rpx 32rpx 0 32rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  border-radius: 0 0 16rpx 16rpx;
  box-shadow: 0 -2rpx 8rpx #f0f0f0;
  min-height: 90rpx;
}

.btn-cancel {
  min-width: 120rpx;
  height: 64rpx;
  line-height: 64rpx;
  margin-right: 24rpx;
  background: #fff;
  color: #666;
  border: 1rpx solid #ccc;
  border-radius: 32rpx;
  text-align: center;
  font-size: 28rpx;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}

.btn-cancel:active {
  background: #f5f5f5;
}

.btn-confirm {
  min-width: 140rpx;
  height: 64rpx;
  line-height: 64rpx;
  background: #0066e6;
  color: #fff;
  border-radius: 32rpx;
  text-align: center;
  font-size: 28rpx;
  font-weight: bold;
  box-shadow: 0 2rpx 8rpx #e0e3ea;
  cursor: pointer;
  transition: background 0.2s;
}

.btn-confirm:active {
  background: #0053b3;
}
.itemn.disabled {
  pointer-events: none;
  opacity: 0.5;
  background: #f5f5f5 !important;
  color: #bbb !important;
  border-color: #eee !important;
}
</style>
